package com.deyinet.bdcms.core.messageConverter;

/**
 * Created by Administrator on 2017/3/27 0027.
 */
import java.io.IOException;
import java.io.InputStream;

import com.deyinet.bdcms.core.bean.FileOutput;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

public class FileOutputMessageConverter extends AbstractHttpMessageConverter<FileOutput> {
    public FileOutputMessageConverter() {
        super(MediaType.ALL);
    }

    protected boolean supports(Class<?> clazz) {
        boolean b = FileOutput.class == clazz;
        return b;
    }

    protected FileOutput readInternal(Class<? extends FileOutput> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return new FileOutput("--");
    }

    protected void writeInternal(FileOutput fileOutput, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        InputStream inputStream = fileOutput.getInputStream();
        if(inputStream != null) {
            outputMessage.getHeaders().set("Content-Disposition", "filename=" + fileOutput.getFilename());
            outputMessage.getHeaders().set("Content-Type", fileOutput.getContentType());
            outputMessage.getBody().write(IOUtils.toByteArray(inputStream));
        } else {
            outputMessage.getBody().write("文件不存在".getBytes());
        }

    }
}

